const modal = require('./modal')
const shema = modal.schema
/**
 * 获取管理员列表
 */
Parse.Cloud.define('getAdministratorList', async (request, response) => {
  try {
    const role = modal.role()
    const querySuperRole = role.query()
    const queryAdminRole = role.query()
    querySuperRole.equalTo('name', 'super')  // 超级管理员
    queryAdminRole.equalTo('name', 'administrator') // 普通管理员

    const findSuperRole = querySuperRole.first()
    const findAdminRole = queryAdminRole.first()

    const superRole = await findSuperRole
    const adminRole = await findAdminRole

    const findSuperUsers = superRole.relation('users').query().find()
    const findAdminUsers = adminRole.relation('users').query().find()
    const superUsers = await findSuperUsers
    const adminUsers = await findAdminUsers

    response.success(superUsers.concat(adminUsers))
  } catch (err) {
    response.error(err.message)
  }
})

Parse.Cloud.define('createWechatUser', async (req, res) => {
  const openid = req.params.openid
  if (!openid) {
    return res.error('无效授权')
  }
  const wechatUser = shema.WechatUser()
  const query = wechatUser.query()
  try {
    const current = await query.equalTo('openid', openid).first()
    if (current) {
      res.success(current)
    } else {
      const user = await wechatUser.save(req.params)
      res.success(user)
    }
  } catch (err) {
    res.error(err.message)
  }
})
Parse.Cloud.beforeSave('_User', async (req, res) => {
  const user = req.object
  const authData = user.get('authData')
  if (authData && authData.wechat) {
    const openid = authData.wechat.id
    const wechatProfile = shema.WechatUser()
    const profileQuery = wechatProfile.query()
    try {
      const currentProfile = await profileQuery.equalTo('openid', openid).first()
      user.set('wechatProfile', currentProfile)
      res.success()
    } catch (err) {
      res.error(err.message)
    }
  } else {
    res.success()
  }
})
Parse.Cloud.afterSave('_User', async (req) => {
  const user = req.object
  console.log(user)
  const authData = user.get('authData')
  if (authData && authData.wechat) {
    const wechatUserId = user.get('wechatProfile').id
    const wechatUserQuery = shema.WechatUser().query()
    const current = await wechatUserQuery.get(wechatUserId)
    const member = shema.member()
    const memberQuery = member.query()
    const currentMember = await memberQuery.equalTo('wechat', current.get('nickname')).first()
    if (currentMember) {
      currentMember.set('user', user)
      await currentMember.save()
    }
  }
})
